﻿using LeSoft.Application.Bussiness;
using LeSoft.Application.Cache;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Mvc;


namespace LeSoft.Application.Web.Areas.ResourceManage.Controllers
{

    public class RS_PStructsController : MvcControllerBase
    {
        private OrganizeCache organizeCache = new OrganizeCache();
        private OrganizeBLL obll = new OrganizeBLL();
        private PStructCache pstructCache = new PStructCache();
        private PStructBLL pstructBLL = new PStructBLL();
        private PropertyBLL probll = new PropertyBLL();
        private PavilionBLL pavbll = new PavilionBLL();
        private FloorBLL fbll = new FloorBLL();
        private RoomBLL rbll = new RoomBLL();
        private GarageBLL gbll = new GarageBLL();
        private List<PStructEntity> ExportList = new List<PStructEntity>();
        private CustomerInfoBLL cinfoBll = new CustomerInfoBLL();
        private RelationPCBLL relationPCBll = new RelationPCBLL();
        private CodeRuleBLL codeRuleBLL = new CodeRuleBLL();
        private PStructFileBLL pstructFileBLL = new PStructFileBLL(); 
        #region 视图

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Form()
        {
            if (Request["keyValue"] == null)
            {
                ViewBag.FCCode = codeRuleBLL.GetBillCode("", "10010");
            }
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Detail()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult RoomDetailList()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult NewIndex()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult BatchForm()
        {
            return View();
        }

        public ActionResult UpdateState()
        {
            return View();
        }

        
        #endregion

        #region 查询数据
        /// <summary>
        /// 获取到某个类型的房产树形列表
        /// </summary>
        /// <param name="organizeId">公司Id</param>
        /// <param name="keyword">关键字</param>
        /// <returns>返回树形Json</returns>
        /// 用于房产树或选择下拉列表树
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取房产树", "GetTreeJsonOld")]
        public ActionResult GetTreeJsonOld(int type = -1, string id = "0", string OrganizeId = "", bool IsSubstep = false)
        {
            var pstructdata = pstructCache.GetList().OrderBy(t => t.Code).ToList();
            var treeList = new List<TreeEntity>();
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = organizeCache.GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                pstructdata = pstructdata.Where(t => organizeids.Contains(t.OrganizeId)).ToList();
            }
            if (!string.IsNullOrEmpty(OrganizeId))
            {
                OrganizeId = organizeCache.GetSonOrganizeId(OrganizeId);
                pstructdata = pstructdata.Where(t => OrganizeId.Contains(t.OrganizeId)).ToList();
            }
            if (type > -1 && pstructdata.Count() > 0)
            {

                if (type == 6) pstructdata = pstructdata.Where(t => Convert.ToInt32(t.Type) <= type && t.Type != 5).ToList();
                else pstructdata = pstructdata.Where(t => Convert.ToInt32(t.Type) <= type).ToList();
            }
            if (pstructdata != null)
            {
                var data = IsSubstep ? pstructdata.Where(t => t.ParentId == id) : pstructdata;
                foreach (PStructEntity item in data)
                {
                    #region 房产
                    TreeEntity tree = new TreeEntity();
                    bool hasChildren = pstructdata.Count(t => t.ParentId == item.Id && item.Type != 5) == 0 ? false : true;
                    tree.id = item.Id;
                    tree.text = item.Name;
                    tree.value = item.OrganizeId;
                    tree.title = item.AllCode;
                    tree.Attribute = "PSAllName";
                    tree.AttributeValue = item.AllName;
                    var ParentId = IsSubstep ? "0" : !string.IsNullOrEmpty(item.ParentId) && item.ParentId != "0" ? item.ParentId : "0";
                    tree.parentId = ParentId;
                    tree.AttributeA = "Type";
                    tree.AttributeValueA = item.Type.ToString();
                    tree.isexpand = false;
                    tree.complete = !IsSubstep;
                    tree.hasChildren = hasChildren;
                    switch (item.Type)
                    {
                        case 1: tree.img = "fa fa-university"; break;
                        case 2: tree.img = "fa fa-building-o"; break;
                        case 4: tree.img = "fa fa-server"; break;
                        case 5: tree.img = "fa fa-cube"; break;
                        default:
                            tree.img = "fa fa-th-list";
                            break;
                    }
                    if (item.ActiveMark == 1)
                        tree.imgstyle = "color:#2df12d";
                    treeList.Add(tree);
                    #endregion
                }
            }
            return Content(treeList.TreeToJson());
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取房产树", "GetTreeJson")]
        public ActionResult GetTreeJson(int type = -1, string id = "0", string OrganizeId = "", bool IsSubstep = false, string queryJson = "")
        {

            var pstructdata = pstructCache.GetList().OrderBy(t => t.Code).ToList();
            var treeList = new List<TreeEntity>();
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = organizeCache.GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                pstructdata = pstructdata.Where(t => organizeids.Contains(t.OrganizeId)).ToList();
            }
            if (!string.IsNullOrEmpty(OrganizeId))
            {
                OrganizeId = organizeCache.GetSonOrganizeId(OrganizeId);
                pstructdata = pstructdata.Where(t => OrganizeId.Contains(t.OrganizeId)).ToList();
            }

            if (type > -1 && pstructdata.Count() > 0)
            {

                if (type == 6) pstructdata = pstructdata.Where(t => Convert.ToInt32(t.Type) <= type && t.Type != 5).ToList();
                else pstructdata = pstructdata.Where(t => Convert.ToInt32(t.Type) <= type).ToList();
            }

            if (pstructdata != null)
            {
                var data = IsSubstep ? pstructdata.Where(t => t.ParentId == id) : pstructdata;
                if (!queryJson.IsEmpty())
                {
                    var queryParam = queryJson.ToJObject();
                    if (!queryParam.IsEmpty())
                    {
                        //是否发布
                        if (!queryParam["IsPublish"].IsEmpty())
                        {
                            data = data.Where(e => e.IsPublish == 2).ToList();
                        }

                    }
                }
                data = data.OrderBy(e => e.Name).ThenBy(e => e.Code);
                int AuthorizeType = 0;
                string AuthorizeData = new AuthorizeDataBLL().GetAuthorizeDataRoomId(1, out AuthorizeType).ToString();
                foreach (PStructEntity item in data)
                {

                    #region 房产
                    TreeEntity tree = new TreeEntity();
                    bool hasChildren = pstructdata.Count(t => t.ParentId == item.Id && item.Type != 5) == 0 ? false : true;
                    tree.id = item.Id;
                    tree.text = item.Name;
                    tree.value = item.OrganizeId;
                    tree.title = item.AllCode;
                    tree.Attribute = "PSAllName";
                    tree.AttributeValue = item.AllName;
                    var ParentId = IsSubstep ? "0" : !string.IsNullOrEmpty(item.ParentId) && item.ParentId != "0" && pstructdata.Count(t => t.Id == item.ParentId) > 0 ? item.ParentId : "0";
                    tree.parentId = ParentId;
                    tree.AttributeA = "Type";
                    tree.AttributeValueA = item.Type.ToString();
                    tree.isexpand = false;
                    tree.complete = !IsSubstep;
                    tree.hasChildren = hasChildren;
                    switch (item.Type)
                    {
                        case 1: tree.img = "fa fa-university"; break;
                        case 2: tree.img = "fa fa-building-o"; break;
                        case 4: tree.img = "fa fa-server"; break;
                        case 5: tree.img = "fa fa-cube"; break;
                        default: tree.img = "fa fa-th-list"; break;
                    }
                    if (item.ActiveMark == 1) tree.imgstyle = "color:#2df12d";
                    if (Config.GetValue("IsAuthorize").ToBool())
                    {
                        if (AuthorizeType == 0) if (AuthorizeData.Contains(item.OrganizeId)) treeList.Add(tree);
                        if (AuthorizeType == 1 || AuthorizeType == 2 || AuthorizeType == 4)
                        {
                            if (AuthorizeData.Contains(item.Id)) treeList.Add(tree);
                        }
                        if (AuthorizeType == -2) treeList.Add(tree);
                    }
                    else
                    {
                        treeList.Add(tree);
                    }

                    #endregion
                }
            }
            return Content(treeList.TreeToJson());
        }

        /// <summary>
        /// 分页获取房产列表数据
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>       
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取房产", "GetPageListJson")]
        public ActionResult GetPageListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var queryParam = queryJson.ToJObject();
            if (!string.IsNullOrEmpty(queryJson))
            {
                if (!queryParam["OrganizeId"].IsEmpty())
                {
                    string OrganizeId = organizeCache.GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                    queryParam["OrganizeId"] = OrganizeId;
                }
                queryJson = queryParam.ToJson();

            }
            var data = pstructBLL.GetPageData(pagination, queryJson);
            var JsonData = new
                {
                    rows = data,
                    total = pagination.total,
                    page = pagination.page,
                    records = pagination.records,
                    costtime = CommonHelper.TimerEnd(watch)
                };
            return Content(JsonData.ToJson());
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取房产统计列表", "GetStatistics")]
        public ActionResult GetStatistics(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            if (!string.IsNullOrEmpty(queryJson))
            {
                var queryParam = queryJson.ToJObject();
                if (!queryParam["OrganizeId"].IsEmpty())
                {
                    string OrganizeId = organizeCache.GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                    queryParam["OrganizeId"] = OrganizeId;
                }
                queryJson = queryParam.ToJson();
            }
            var data = pstructBLL.GetStatistics(pagination, queryJson);
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取数据列表2", "GetStatisticsTotal")]
        public ActionResult GetStatisticsTotal(string queryJson)
        {
            if (!string.IsNullOrEmpty(queryJson))
            {
                var queryParam = queryJson.ToJObject();
                if (!queryParam["OrganizeId"].IsEmpty())
                {
                    string OrganizeId = organizeCache.GetSonOrganizeId(queryParam["OrganizeId"].ToString());
                    queryParam["OrganizeId"] = OrganizeId;
                }
                queryJson = queryParam.ToJson();
            }
            return Content(pstructBLL.GetStatisticsTotal(queryJson).ToJson());
        }

        /// <summary>
        /// 获取房产实体
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetForm, "获取房产表单", "GetFormInfoJson")]
        public ActionResult GetFormInfoJson(string keyValue)
        {
            try
            {
                var data = pstructBLL.GetEntity(keyValue);
                object obj = null;
                switch (data.Type)
                {
                    case 1: obj = new { data = data, model = pstructBLL.GetPropertyEntity(keyValue), FileList = pstructFileBLL.GetList(keyValue) }; break;
                    case 2: obj = new { data = data, model = pstructBLL.GetPavilionEntity(keyValue), FileList = pstructFileBLL.GetList(keyValue) }; break;
                    case 3: obj = new { data = data, model = pstructBLL.GetGarageEntity(keyValue), FileList = pstructFileBLL.GetList(keyValue) }; break;
                    case 4: obj = new { data = data, model = pstructBLL.GetFloorEntity(keyValue), FileList = pstructFileBLL.GetList(keyValue) }; break;
                    case 5: obj = new { data = data, model = pstructBLL.GetRoomEntity(keyValue), FileList = pstructFileBLL.GetList(keyValue), pType = data.ParentId != "0" && !string.IsNullOrEmpty(data.ParentId) ? pstructBLL.GetEntity(data.ParentId).Type : 0 }; break;
                    default:
                        break;
                }
                return Content(obj.ToJson());
            }
            catch (Exception)
            {
                return Error("获取数据失败");
            }
        }

        /// <summary>
        /// 获取房产列表(房间使用名称显示)
        /// </summary>
        /// <param name="organizeId">公司Id</param>
        /// <returns>返回树形Json</returns>
        /// 用于维修装修等选客户的
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "获取带名字的房产树", "GetTreeNameJson")]
        public ActionResult GetTreeNameJson(string id = "0", string OrganizeId = "", bool IsSubstep = false)
        {

            var data = pstructCache.GetList().Where(t => t.Type <= 5).OrderBy(t => t.Type).OrderBy(t => t.Code).ToList();
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = organizeCache.GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                data = data.Where(t => organizeids.Contains(t.OrganizeId)).ToList();
            }
            if (!string.IsNullOrEmpty(OrganizeId))
            {
                var organizeids = organizeCache.GetSonOrganizeId(OrganizeId);
                data = data.Where(t => organizeids.Contains(t.OrganizeId)).ToList();
            }
            var treeList = new List<TreeEntity>();
            if (data != null)
            {
                var pstructdata = IsSubstep ? data.Where(t => t.ParentId == id) : data;
                foreach (PStructEntity item in pstructdata)
                {
                    TreeEntity tree = new TreeEntity();
                    bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                    #region treename
                    if (item.Type == 5)
                    {
                        var relationpc = relationPCBll.GetPStructIdByEntity(item.Id);
                        if (relationpc == null)
                        {
                            tree.text = item.Name;
                            item.ActiveMark = 0;
                        }
                        else
                        {
                            var model = cinfoBll.GetEntity(relationpc.CustomerId);
                            if (model == null)
                            {
                                tree.text = item.Name;
                                item.ActiveMark = 0;
                            }
                            else
                            {
                                tree.text = item.Name + "&lt" + model.Name + "&gt"; item.ActiveMark = 1;
                                tree.Attribute = "RelationPCId";
                                tree.AttributeValue = relationpc.Id;
                            }
                        }
                    }
                    else
                        tree.text = item.Name;
                    #endregion
                    tree.id = item.Id;
                    tree.value = item.OrganizeId;
                    var ParentId = IsSubstep ? "0" : !string.IsNullOrEmpty(item.ParentId) && item.ParentId != "0" ? item.ParentId : "0";
                    tree.parentId = ParentId;
                    switch (item.Type)
                    {
                        case 1: tree.img = "fa fa-university"; break;
                        case 2: tree.img = "fa fa-building-o"; break;
                        case 4: tree.img = "fa fa-server"; break;
                        case 5: tree.img = "fa fa-cube"; break;
                        default:
                            tree.img = "fa fa-th-list";
                            break;
                    }
                    if (item.ActiveMark == 1)
                        tree.imgstyle = "color:#2df12d";
                    tree.isexpand = false;
                    tree.complete = !IsSubstep;
                    tree.hasChildren = hasChildren;
                    tree.Attribute = "PSAllName";
                    tree.AttributeValue = item.AllName;
                    tree.AttributeA = "Type";
                    tree.AttributeValueA = item.Type.ToString();
                    treeList.Add(tree);
                }
            }

            return Content(treeList.TreeToJson());
        }



        /// <summary>
        /// 递归查询下级组织机构 
        /// </summary>
        /// <param name="organizeid">组织机构ID</param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "递归查询下级组织机构", "RecursiveOrganize")]
        private List<OrganizeEntity> RecursiveOrganize(string organizeid)
        {
            var organizedata = organizeCache.GetList();
            if (!string.IsNullOrEmpty(organizeid))
            {
                List<OrganizeEntity> list = new List<OrganizeEntity>();
                foreach (var item in organizedata.Where(t => t.ParentId == organizeid))
                {
                    if (organizedata.Count(t => t.ParentId == item.OrganizeId) > 0)
                    {
                        list.AddRange(RecursiveOrganize(item.OrganizeId));
                    }
                    list.Add(item);
                }
                return list;
            }
            else
                return organizedata.ToList();
        }


        /// <summary>
        /// 获取经纬度
        /// </summary>
        /// <param name="address">完整地址</param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetForm, "获取经纬度", "GetGeocoding")]
        public ActionResult GetGeocoding(string address)
        {
            return Content(new PDGZFAPIBLL().GetGeocoding(address));
            //return null;
        }

        #endregion





        /// <summary>
        /// 房产列表
        /// </summary>
        /// <param name="condition">查询条件</param>
        /// <param name="keyword">关键字</param>
        /// <returns>返回树形列表Json</returns>
        /// 用于表格展示
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "房产列表", "GetTreeListJson")]
        public ActionResult GetTreeListJson(string condition, string keyword, string PstructId, string organizeid = "")
        {
            bool isNullOrEmpty = string.IsNullOrEmpty(PstructId);
            var organizedata = RecursiveOrganize(organizeid);
            if (OperatorProvider.Provider.Current().UserId != "System")
                organizedata = organizedata.Where(t => t.OrganizeId == OperatorProvider.Provider.Current().CompanyId).ToList();
            if (!string.IsNullOrEmpty(organizeid))
            {
                var model = organizeCache.GetList().FirstOrDefault(t => t.OrganizeId == organizeid);
                organizedata.Add(model);
            }
            var organizeList = organizedata.Select(t => new
               {
                   t.Address,
                   t.OrganizeId,
                   t.ParentId,
                   Name = t.FullName,
                   Code = t.EnCode
               });
            var propertydata = probll.GetList();
            var pstructdata = pstructBLL.GetList().Where(t => t.Type != 6).OrderBy(t => t.Code).ToList();
            if (!isNullOrEmpty)
            {
                pstructdata = pstructdata.Where(t => t.AllCode.Contains(PstructId)).ToList();
            }
            if (!string.IsNullOrEmpty(keyword) && !string.IsNullOrEmpty(condition))
            {
                switch (condition)
                {
                    case "Name":
                        pstructdata = pstructdata.TreeWhere(t => t.Name.Contains(keyword), "Id"); break;
                    case "Code":
                        pstructdata = pstructdata.TreeWhere(t => t.Code.Contains(keyword), "Id"); break;
                }
            }
            var dataPstruct = (from a in pstructdata
                               join b in probll.GetList() on a.Id equals b.PStructId
                               into temp
                               from ab in temp.DefaultIfEmpty()
                               join c in pavbll.GetList() on a.Id equals c.PStructId
                               into temp1
                               from ac in temp1.DefaultIfEmpty()
                               join d in fbll.GetList() on a.Id equals d.PStructId
                               into temp2
                               from ad in temp2.DefaultIfEmpty()
                               join e in rbll.GetList() on a.Id equals e.PStructId
                               into temp3
                               from ae in temp3.DefaultIfEmpty()
                               join f in gbll.GetList() on a.Id equals f.PStructId
                               into temp4
                               from af in temp4.DefaultIfEmpty()
                               select new
                               {
                                   a.Id,
                                   a.ParentId,
                                   a.Type,
                                   a.TypeId,
                                   a.AllCode,
                                   a.AllName,
                                   a.OrganizeId,
                                   a.Code,
                                   a.Name,
                                   Area = ab != null ? ab.Area : ac != null ? ac.CoverArea : ad != null ? ad.Area : ae != null ? ae.Area : af != null ? af.Area : 0,
                                   Memo = ab != null ? ab.Memo : ac != null ? ac.Memo : ad != null ? ad.Memo : ae != null ? ae.Memo : af != null ? af.Memo : "0",
                                   AuditMark = ab != null ? ab.AuditMark : ac != null ? ac.AuditMark : ad != null ? ad.AuditMark : ae != null ? ae.AuditMark : af != null ? af.AuditMark : 0,
                               }).OrderBy(t => t.Code).ToList();
            var treeList = new List<TreeGridEntity>();
            if (isNullOrEmpty)
            {
                foreach (var item in organizeList)
                {
                    #region 机构
                    TreeGridEntity tree = new TreeGridEntity();
                    bool hasChildren = organizedata.Count(t => t.ParentId == item.OrganizeId) == 0 ? false : true;
                    if (hasChildren == false)
                    {
                        hasChildren = dataPstruct.Count(t => t.OrganizeId == item.OrganizeId) == 0 ? false : true;
                    }
                    tree.id = item.OrganizeId;
                    tree.hasChildren = hasChildren;
                    tree.parentId = item.OrganizeId == organizeid ? "0" : item.ParentId;
                    tree.expanded = true;
                    string itemJson = item.ToJson();
                    itemJson = itemJson.Insert(1, "\"PStructId\":\"" + item.OrganizeId + "\",");
                    itemJson = itemJson.Insert(1, "\"Sort\":\"Organize\",");
                    tree.entityJson = itemJson;
                    treeList.Add(tree);
                    #endregion
                }
            }
            foreach (var item in dataPstruct)
            {
                #region 房产
                TreeGridEntity tree = new TreeGridEntity();
                bool hasChildren = dataPstruct.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id;
                if (item.ParentId == "0" && isNullOrEmpty)
                {
                    tree.parentId = item.OrganizeId;
                }
                else
                {
                    tree.parentId = dataPstruct.Count(t => t.Id == item.ParentId) == 0 ? "0" : item.ParentId;
                }
                tree.expanded = false;
                tree.hasChildren = hasChildren;
                string itemJson = item.ToJson();
                itemJson = itemJson.Insert(1, "\"Sort\":\"PStruct\",");
                tree.entityJson = itemJson;
                treeList.Add(tree);
                #endregion
            }
            return Content(treeList.TreeJson());
        }


        /// <summary>
        /// 根据类型获取树
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        /// 用于巡更路线
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "类型获取树", "GetTypeTreeJson")]
        public ActionResult GetTypeTreeJson(string type, string OrganizeId)
        {
            var data = pstructCache.GetList();
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = organizeCache.GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                data = data != null ? data.Where(t => organizeids.Contains(t.OrganizeId)).ToList() : null;
            }
            if (!string.IsNullOrEmpty(OrganizeId))
            {
                var organizeids = organizeCache.GetSonOrganizeId(OrganizeId);
                data = data != null ? data.Where(t => organizeids.Contains(t.OrganizeId)).ToList() : null;
            }
            var treeList = new List<TreeEntity>();
            data = data.Where(t => t.Type.ToString() == type);
            foreach (PStructEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                tree.id = item.Id;
                tree.text = item.Name;
                tree.value = item.Id;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = false;
                tree.parentId = "0";
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }

        #region 验证数据
        /// <summary>
        /// 编号不能重复
        /// </summary>
        /// <param name="enCode">编号</param>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        public ActionResult ExistCode(string Code, string keyValue)
        {
            bool IsOk = pstructBLL.ExistEnCode(Code, keyValue);
            return Content(IsOk.ToString());
        }
        /// <summary>
        /// 名称不能重复
        /// </summary>
        /// <param name="FullName">名称</param>
        /// <param name="keyValue">主键</param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        public ActionResult ExistName(string Name, string keyValue)
        {
            bool IsOk = pstructBLL.ExistFullName(Name, keyValue);
            return Content(IsOk.ToString());
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 保存房产表单（新增、修改）
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="pstructEntity">房产实体</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "保存房产", "SaveForm")]
        public ActionResult SaveForm(string keyValue, int Type, string BaseInfo, string PProperty, string PPavilion, string PGarage, string PFloor, string PRoom, string list)
        {
            try
            {

                PStructEntity psdata = BaseInfo.ToObject<PStructEntity>();//房产结构
                PropertyEntity prodata = null;//楼盘
                PavilionEntity pavdata = null;//楼阁/楼栋/单元/梯
                GarageEntity gdata = null;//车库/广告位区域/场地区域/冷库
                FloorEntity fdata = null;//楼层/网点
                MultipleRoom rdata = null;//房间/床位
                List<PStructFileEntity> ListFile = list.ToObject<List<PStructFileEntity>>();
                switch (Type)
                {
                    case 1: prodata = PProperty.ToObject<PropertyEntity>();
                        break;
                    case 2: pavdata = PPavilion.ToObject<PavilionEntity>();
                        break;
                    case 3: gdata = PGarage.ToObject<GarageEntity>();
                        break;
                    case 4: fdata = PFloor.ToObject<FloorEntity>();
                        break;
                    case 5: rdata = PRoom.ToObject<MultipleRoom>();
                        break;
                    default:
                        break;
                }



                pstructBLL.SaveForm(keyValue, Type, psdata, prodata, pavdata, gdata, fdata, rdata, ListFile);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error("操作失败。");
                throw;
            }
        }
        /// <summary>
        /// 删除房产
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Delete, "删除房产", "RemoveForm")]
        public ActionResult RemoveForm(string keyValue)
        {
            var data = pstructBLL.GetList().Where(t => t.ParentId == keyValue).ToList();
            if (data.Count > 0)
            {
                return Error("请先删除子节点");
            }
            else
            {
                var entity = pstructBLL.GetEntity(keyValue);
                if (entity != null)
                {
                    pstructBLL.RemoveForm(keyValue);
                    return Success("操作成功。");
                }
                else
                {
                    return Error("无法删除组织机构的数据");
                }
            }
        }

        /// <summary>
        /// 改变房间状态
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Submit, "改变房间状态", "UpdateState")]
        public ActionResult UpdateState(string keyValue, int State)
        {
            try
            {
                new RoomBLL().UpdateState(keyValue, State);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error("操作失败。");
                throw;
            }
        }
        #endregion

        #region 文件上传
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="Filedata">文件对象</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Other, "上传文件", "UploadifyFile")]
        public ActionResult UploadifyFile(HttpPostedFileBase Filedata)
        {
            try
            {
                Thread.Sleep(500);////延迟500毫秒
                //没有文件上传，直接返回
                if (Filedata == null || string.IsNullOrEmpty(Filedata.FileName) || Filedata.ContentLength == 0)
                {
                    return HttpNotFound();
                }
                //获取文件完整文件名(包含绝对路径)
                //文件存放路径格式：/Resource/ResourceFile/{userId}{data}/{guid}.{后缀名}
                string userId = OperatorProvider.Provider.Current().UserId;
                string fileGuid = Guid.NewGuid().ToString();
                long filesize = Filedata.ContentLength;
                string FileEextension = Path.GetExtension(Filedata.FileName);
                string uploadDate = DateTime.Now.ToString("yyyyMMdd");
                string virtualPath = string.Format("~\\Resource\\PStructFile\\{0}\\{1}{2}{3}", userId, uploadDate, fileGuid, FileEextension);
                string fullFileName = this.Server.MapPath(virtualPath);
                //创建文件夹
                string path = Path.GetDirectoryName(fullFileName);
                Directory.CreateDirectory(path);
                PStructFileEntity psfe = new PStructFileEntity();
                if (!System.IO.File.Exists(fullFileName))
                {
                    //保存文件
                    Filedata.SaveAs(fullFileName);
                    //文件信息写入数据库

                    psfe.Create();
                    psfe.FileType = 2;
                    psfe.FileName = Filedata.FileName;
                    string URL = Request.Url.ToString().Replace(Request.RawUrl, "/");
                    psfe.FileUrl = Server.MapPath(virtualPath).Replace(HttpRuntime.AppDomainAppPath, URL);
                    pstructFileBLL.SaveForm("", psfe);
                }
                return Content("{\"Id\":\"" + psfe.Id + "\"}");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// 上传主图
        /// </summary>
        /// <param name="Filedata">文件对象</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Other, "上传主图", "UploadifyFile1")]
        public ActionResult UploadifyFile1(HttpPostedFileBase Filedata)
        {
            try
            {
                Thread.Sleep(500);////延迟500毫秒
                //没有文件上传，直接返回
                if (Filedata == null || string.IsNullOrEmpty(Filedata.FileName) || Filedata.ContentLength == 0)
                {
                    return HttpNotFound();
                }
                //获取文件完整文件名(包含绝对路径)
                //文件存放路径格式：/Resource/ResourceFile/{userId}{data}/{guid}.{后缀名}
                string userId = OperatorProvider.Provider.Current().UserId;
                string fileGuid = Guid.NewGuid().ToString();
                long filesize = Filedata.ContentLength;
                string FileEextension = Path.GetExtension(Filedata.FileName);
                string uploadDate = DateTime.Now.ToString("yyyyMMdd");
                string virtualPath = string.Format("~\\Resource\\PStructFile\\{0}\\{1}\\{2}{3}", userId, uploadDate, fileGuid, FileEextension);
                string fullFileName = this.Server.MapPath(virtualPath);
                //创建文件夹
                string path = Path.GetDirectoryName(fullFileName);
                Directory.CreateDirectory(path);
                string FileUrl = "";
                if (!System.IO.File.Exists(fullFileName))
                {
                    //保存文件
                    Filedata.SaveAs(fullFileName);
                    string URL = Request.Url.ToString().Replace(Request.RawUrl, "/");
                    FileUrl = Server.MapPath(virtualPath).Replace(HttpRuntime.AppDomainAppPath, URL);
                }
                return Content(FileUrl);
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }
        #endregion


        #region 数据导出
        /// <summary>
        /// 房产资料导出
        /// </summary>
        public ActionResult GetExportList(string queryJson)
        {
            new ExportBLL().GetExportList((int)ExportType.PStruct, queryJson);
            return Success("导出成功。");
        }
        #endregion




    

    }
}
